/**
 * Copyright phonemap.com
 *
 * Licensed under the phonemap.com License, Version 1.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.phonemap.com/licenses/LICENSE-1.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
var map;
var homePosition;
var markers = Array();
var infoWindows = Array();
var historyMakers = Array();
var historyLabels = Array();
var flightPath = null;
var oldIdx = -1;

/**
 * After Login.
 */
function afterLogin() {
	// Step 01: load map
	google.maps.event.addDomListener(window, 'resize', initMap);
	google.maps.event.addDomListener(window, 'load', initMap);

	// //Step 02: load info for the first time log in
	initMap();
}
/**
 * Draws Flight.
 * @param positions
 */
function drawFlight(positions) {
	clearHistory();
	if (positions.length > 0) {
		var position = positions[0];
		var pos = getLatLng(position.located);
		var marker = new google.maps.Marker({
			position : pos,
			map : map,
			title : position.located,
			draggable : false,
//			animation : google.maps.Animation.BOUNCE,
			infoWindowIndex : i
		});
		label = new Label({
			map : map,
			title : 'Start [' +position.located_time+']'
		});
		label.bindTo('position', marker, 'position');
		label.bindTo('text', marker, 'position');
		historyMakers.push(marker);
		historyLabels.push(label);
		//flightPath.push(pos);
		
		var flightPlanCoordinates = new google.maps.MVCArray();
		flightPlanCoordinates.push(pos);
		for (var i = 1; i < positions.length; i++) {
			position = positions[i];
			pos = getLatLng(position.located);
			flightPlanCoordinates.push(pos);
			
			//Draws makers
			var marker = new google.maps.Marker({
				position : pos,
				map : map,
				title : position.located,
				draggable : false,
//				animation : google.maps.Animation.BOUNCE,
				infoWindowIndex : i
			});
			label = new Label({
				map : map,
				title : '[' +position.located_time+']'
			});
			label.bindTo('position', marker, 'position');
			label.bindTo('text', marker, 'position');
			historyMakers.push(marker);
			historyLabels.push(label);
		}
		
		flightPath = new google.maps.Polyline({
			path : flightPlanCoordinates,
			geodesic : true,
			strokeColor : '#FF0000',
			strokeOpacity : 1.0,
			strokeWeight : 2
		});

		flightPath.setMap(map);
	}
	
}

/**
 * Clear history.
 */
function clearHistory() {
	if (oldIdx != -1) {
		infoWindows[oldIdx].close();
	}
	if (historyMakers) {
		for (i in historyMakers) {
			historyMakers[i].setMap(null);
			historyLabels[i].onRemove();
		}

		historyMakers = new Array();
		historyLabels = new Array();
	}
	if (flightPath != null) {
		flightPath.setMap(null);
	}
}
/**
 * Renders history.
 * 
 * @param positions
 */
function renderHistory(positions) {
	clearHistory();
	for (var i = 0; i < positions.length - 1; i++) {
		var position = positions[i];
		pos = getLatLng(position.located);
		var marker = new google.maps.Marker({
			position : pos,
			map : map,
			title : position.located,
			draggable : false,
//			animation : google.maps.Animation.BOUNCE,
			infoWindowIndex : i
		});
		label = new Label({
			map : map,
			title : i
		});
		label.bindTo('position', marker, 'position');
		label.bindTo('text', marker, 'position');
		historyMakers.push(marker);
		historyLabels.push(label);
	}
}

/**
 * Gets User Id.
 * 
 * @param userId
 */
function getPosition(userId) {
	$.ajax({
		url : "/follow?action=getHitory&userId=" + userId,
		type : 'GET',
		data : '',
		success : function(resp) {
			if (resp != null) {
				// getting the data from the response object
				var data = resp.data;
				
				// initialize map
				if (data.length > 0) {
//					renderHistory(data);
					drawFlight(data);
				}
			}
		},
		error : function(resp) {
			alert('Cannot get data! Please check again');
		}
	});
}

/**
 * get Popup info of avatar
 * @param user
 * @returns {String}
 */
function getPopupInfo(user) {
	var online = isOnline(user.located_time) == true ? 'online' : 'offline';
	var gender = user.gender != NULL ? user.gender : 'Unknown';
	var info = '<div><ul>'
			+ '<li><a href=\''
			+ user.link
			+ '\'  target=\'_blank\'>'
			+ user.fullname
			+ '</a></li>'
			+ '<li>'
			+ gender
			+ '</li>'
			+ '<li>'
			+ user.located_time
			+ '</li>'
			+ '<li><a href=\"#\" style=\"color:#2EA620;\" onclick=\"getPosition('
			+ user.user_id + ')\">Show History</a></li>' + '</ul></div>';
	return info;
} 

/**
 * load map with users
 */
function loadMap(users) {
	
	//Get user login to initialize map
	var user = users[0];
	markers = Array();
	infoWindows = Array();
	
	//Set profile
	setProfile(user);
	
	//set map options
	var mapOptions
	if (user.located == NULL) {
		mapOptions = {
				zoom : 8,
				center : new google.maps.LatLng(40.111689,-78.134766),//new york
				mapTypeId : google.maps.MapTypeId.ROADMAP
			};
		homePosition = new google.maps.LatLng(40.111689,-78.134766);
		//load map with user's position
		map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
	} else {
		homePosition = getLatLng(user.located);
		// Set global variable
		oldPos = homePosition;
		timezone = user.timezone;
		
		mapOptions = {
				zoom : 8,
				center : homePosition,
				mapTypeId : google.maps.MapTypeId.ROADMAP
			};
		//load map with user's position
		map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
		
		// Set the last users
		for ( var i = 0; i < users.length; i++) {
			
			var user = users[i];
			var avatar = getAvatar(user);
			var image = getIcon(avatar);
			var pos = getLatLng(user.located);
			var label;
			if (i == 0) {
				var marker = new google.maps.Marker({
				     position: pos,
				     map: map,
				     icon: image,
				     title: user.username,
				     draggable: false,
//				     animation: google.maps.Animation.BOUNCE,
				     infoWindowIndex : i
				 });
				label = new Label({
			        map: map,
			        title: user.fullname
			      });
			} else {
				var marker = new google.maps.Marker({
				     position: pos,
				     map: map,
				     icon: image,
				     title: user.username,
				     draggable: false,
				     infoWindowIndex : i
				 });
				var dist = distance(homePosition.lat(), homePosition.lng(), pos.lat(), pos.lng(), 'K');
			    label = new Label({
			        map: map,
			        title: user.fullname + ' ('+ formatRound(dist) +')'
			      });
			}
			
			
		    
		    label.bindTo('position', marker, 'position');
		    label.bindTo('text', marker, 'position');
		    
		    var info = getPopupInfo(user);
		    infoWindow = new google.maps.InfoWindow({
				content : info
			});
			//google.maps.event.addListener(marker[i], "click", function (e) { iw[i].open(map, marker[i]); });
		    google.maps.event.addListener(marker, "click",function(e) {
		    	if (oldIdx != -1) {
		    		infoWindows[oldIdx].close();
				}
				infoWindows[this.infoWindowIndex].open(map, this);
				oldIdx = this.infoWindowIndex;
			});
			
			infoWindows.push(infoWindow);
			markers.push(marker);
		}
		
	}
	
}

/**
 * init Map
 */
function initMap() {
	
	//load user account from cookie
	var useraccount = $.cookie('useraccount');
	if (useraccount != '' && useraccount != null) {
		      
		$.ajax({
			url : "/follow?action=getFollows&userId="+useraccount,
			type: 'GET',
	        data: '',
			success : function(resp) {
				if (resp != null) {
					// getting the data from the response object
					var data = resp.data;
					
					//initialize map
					if(data.length > 0)
						loadMap(data);
				}
			},
			error : function(resp){
				alert('Cannot get data! Please check again');
			}
		});
	} else {//not login
		//Go to index page
		document.location.href = '/index.html';
	}
}

/**
 * Move the first maker
 */
function moveMapToFirtMaker() {
	map.panTo(homePosition);
}

